package de.fh.ka.as.car.drivecontrol;

import java.io.IOException;

import android.os.Bundle;
import android.util.Log;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;

import de.fh.ka.as.car.drivecontrol.model.Control;

public class RemoteControlledCar extends RealCar {
	private Server server;
	private Kryo kryo;
	public static final int PORT = 5000;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		startServer();
	}

	public void onDestroy() {
		super.onDestroy();

		// close all network connection
		Connection[] connections = server.getConnections();
		if (connections != null) {
			for (Connection connection : connections) {
				if (connection.isConnected())
					connection.close();
			}
		}
		// stop server
		server.stop();
	}

	public void startServer() {
		server = new Server();
		server.start();
		try {
			server.bind(54555, 54777);
		} catch (IOException e) {
			control = new Control();
			e.printStackTrace();
		}

		kryo = server.getKryo();
		kryo.register(Control.class);

		server.addListener(new Listener() {
			public void received(Connection connection, Object object) {
				if (object instanceof Control) {
					control((Control) object);
					Log.i("IOIONetwork", "Serverrevieved: " + control);
					// view2.invalidate();
				}
			}
		});

	}
}
